# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/24 5:34 下午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : 滑动窗口算法.py
# @Software: PyCharm

import wave
import pylab as pl
import numpy as np
import datetime


# 打开WAV文档
f = wave.open(r"../record_audio/output.wav", "rb")
# 读取格式信息
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
print(f'通道数:{nchannels}')
print(f'sampwidth:{sampwidth}')
print(f'采样率:{framerate}')
print(f'总帧数:{nframes}')
# 读取波形数据
str_data = f.readframes(nframes)
f.close()
#将波形数据转换为数组
wave_data = np.fromstring(str_data, dtype=np.short)
# for i in wave_data:
#     print(i)
wave_data.shape = -1, nchannels
wave_data = wave_data.T
# wave_data[abs(wave_data) < 200] = 0
wave_data[abs(wave_data) < 150] = 0
time = np.arange(0, nframes) * (1.0 / framerate)


# 绘制波形

pl.subplot(211)
pl.plot(time, wave_data[0])

data = wave_data[0]
d_time = time

k_word = np.zeros(3, dtype=int)

result = []
tpm = []

time_result = []
time_tpm = []

start_time = datetime.datetime.now()

for i in range(0, len(data) - 2):
    window = data[i:i+3]
    time_window = d_time[i:i+3]
    if (window == k_word).all():
        if len(tpm) == 0:
            tpm = window
            time_tpm = time_window
        else:
            tpm = np.append(tpm, window[-1])
            time_tpm = np.append(time_tpm, time_window[-1])
    else:
        if len(tpm) == 0:
            continue
        else:
            result.append(tpm)
            tpm = []

            time_result.append(time_tpm)
            time_tpm = []
            continue

end_time = datetime.datetime.now()

run_time = end_time - start_time
print('运行时长：', run_time)


for i in range(0, len(time_result)):
    if len(time_result[i]) > 11025:
        pl.plot(time_result[i], result[i], c="r")


pl.xlabel("time (seconds)")
pl.show()
